//
//  NSFileManager+Add.m
//  WuYeUser
//
//  Created by Saxon on 2018/3/9.
//  Copyright © 2018年 com.WuyeUser.remotevillage. All rights reserved.
//

#import "NSFileManager+Add.h"
#import "NSDictionary+SetNilStr.h"

#define DOUCMENTS_PATH NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).lastObject

@implementation NSFileManager (Add)

+ (void)filePutContents:(NSString *)fileName data:(id)data
{
    [self creatDir:@"data"];
    
    NSString *path = [DOUCMENTS_PATH stringByAppendingString:[NSString stringWithFormat:@"/data/%@.plist",fileName]];
    
    BOOL flag = [data writeToFile:path atomically:YES];
    
    if (!flag) {
        //子线程进行数据处理
        dispatch_async(dispatch_queue_create(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            id newData = [NSDictionary changeType:data];
            dispatch_async(dispatch_get_main_queue(), ^{
                BOOL flag = [newData writeToFile:path atomically:YES];
                NSLog(@"%@----%d", fileName, flag);
            });
        });
    } else
        NSLog(@"%@----%d", fileName, flag);
}
+ (BOOL)creatDir:(NSString *)dir
{
    
    NSFileManager *file = [NSFileManager defaultManager];
    NSString *testDirectory = [NSHomeDirectory() stringByAppendingPathComponent:[NSString stringWithFormat:@"/Documents/%@",dir]];
    // 创建目录
    BOOL res=[file createDirectoryAtPath:testDirectory withIntermediateDirectories:YES attributes:nil error:nil];
    if (res) {
        return YES;
    }else
        NSLog(@"文件夹创建失败");
    return NO;
}
+ (id)fileGetContents:(NSString *)fileName type:(BOOL)type
{
    NSFileManager *file = [NSFileManager defaultManager];
    NSString *path = [DOUCMENTS_PATH stringByAppendingString:[NSString stringWithFormat:@"/data/%@.plist",fileName]];
    if ([file fileExistsAtPath:path]) {
        id dic = type ? [NSArray arrayWithContentsOfFile:path] : [NSDictionary dictionaryWithContentsOfFile:path] ;
        
        return dic;
    }
    return nil;
}
+ (void)removePlistFile:(NSString *)fileName
{
    NSFileManager *file = [NSFileManager defaultManager];
    NSString *path = [DOUCMENTS_PATH stringByAppendingString:[NSString stringWithFormat:@"/data/%@.plist",fileName]];
    BOOL flag = [file removeItemAtPath:path error:nil];
    NSLog(@"%@----%d", fileName, flag);
}
+ (void)removeAllPlistFile
{
    NSFileManager *fm = [NSFileManager defaultManager];
    NSString *filePath = [DOUCMENTS_PATH stringByAppendingString:@"/data/"];
    NSArray* subFiles = [fm subpathsAtPath:filePath];
    
    for (NSString* fileName in subFiles) {
        if ([fileName hasSuffix:@"plist"]) {
            [fm removeItemAtPath:[NSString stringWithFormat:@"%@%@", filePath, fileName] error:nil];
        }
    }
}

@end
